package com.wlper.lib.sys;

import java.lang.reflect.Field;

import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;

/**
 * 获取屏幕的相关参数。
 * 
 * @author LWL_Private
 * @date 2014-6-7
 */
public class Screen {
    private static Screen mScreen;
    private Context mContext;

    private static int mScreenWidth, mScreenHeight, mStatusBarHeight,
            mDensityDpi;
    private static float mDensity;

    private Screen(Context context) {
        mContext = context;
    }

    public static Screen getInstance(Context context) {
        if (mScreen == null) {
            synchronized (Screen.class) {
                if (mScreen == null)
                    mScreen = new Screen(context);
            }
        }
        return mScreen;
    }

    private void getScreenParams() {
        DisplayMetrics dm = new DisplayMetrics();
        dm = mContext.getResources().getDisplayMetrics();
        mScreenWidth = dm.widthPixels;
        mScreenHeight = dm.heightPixels;
        mDensityDpi = dm.densityDpi;
        mDensity = dm.density;
    }

    /**
     * 获取屏幕宽度
     * 
     * @return
     */
    public int getScreenWidth() {
        if (mScreenWidth == 0)
            getScreenParams();
        return mScreenWidth;
    }

    /**
     * 获取屏幕高度。不包含状态栏高度值和标题栏高度值。
     * 
     * @return
     */
    public int getScreenHeight() {
        if (mScreenHeight == 0)
            getScreenParams();
        return mScreenHeight;
    }

    /**
     * 获取屏幕密度的绝对值。代表了每英寸屏幕存在的像素数量。
     * 
     * @return
     */
    public int getDenistyDpi() {
        if (mDensityDpi == 0)
            getScreenParams();
        return mDensityDpi;
    }

    /**
     * 获取屏幕密度的相对值。以Dpi = 160为参考值，计算比例。 例如：Dpi=160的屏幕，该值就等于1，Dpi=240的屏幕，该值就等于1.5。
     * 
     * @return
     */
    public float getDenisty() {
        if (mDensity == 0)
            getScreenParams();
        return mDensity;
    }

    /**
     * 获取状态栏高度
     * 
     * @return
     */
    public int getStatusBarHeight() {
        if (mStatusBarHeight == 0) {
            // 用反射的方式来获取状态栏高度
            Class<?> c = null;
            Object obj = null;
            Field field = null;
            int x = 0;
            try {
                c = Class.forName("com.android.internal.R$dimen");
                obj = c.newInstance();
                field = c.getField("status_bar_height");
                x = Integer.parseInt(field.get(obj).toString());
                mStatusBarHeight = mContext.getResources()
                        .getDimensionPixelSize(x);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return mStatusBarHeight;
    }

    public int dpToPx(int dp) {
        return (int) (dp * mDensity);
    }

    public int pxToDp(int px) {
        return (int) (px / mDensity);
    }
}
